
PROJECT=rs232-tempsensor
PORT="/dev/ttyACM0"
CLOCK="16000000UL"
GCC_DEVICE="attiny85"
PGM_DEVICE="t85"
PGM_PROTO="avrispv2"
GCC_OPTIMISATION="-Os"
#GCC_OPTIMISATION="-O2"
PROGRAM_FUSES=0

# NOTE: the -S flag allows inline assembler code to be expanded rather than called and returned (saves cycles)

echo "compile program"
if avr-gcc -g $GCC_OPTIMISATION -Wall -mcall-prologues -DF_CPU=$CLOCK -mmcu=$GCC_DEVICE -c -o $PROJECT.o $PROJECT.c
then
  echo "ok"
else
  echo "failed!"
  exit 1
fi

echo "create object file"
if avr-gcc -g $GCC_OPTIMISATION -Wall -mcall-prologues -DF_CPU=$CLOCK -mmcu=$GCC_DEVICE $PROJECT.o -o $PROJECT.obj
then
  echo "ok"
else
  echo "failed!"
  exit 1
fi

echo "convert object file to hex file"
if avr-objcopy  -R .eeprom -O ihex $PROJECT.obj $PROJECT.hex
then
  echo "ok"
else
  echo "failed!"
  exit 1
fi

echo "erase chip"
if avrdude -c $PGM_PROTO -P $PORT -p $PGM_DEVICE -e
then
  echo "ok"
else
  echo "failed!"
  exit 1
fi

echo "write program to chip"


#
#   FUSE BYTES
#

# read the fuse bytes
echo "Current chip's fuse bytes:"

avrdude -c $PGM_PROTO -P $PORT -p $PGM_DEVICE -U hfuse:r:high.txt:s -U lfuse:r:low.txt:s
echo "-- High Fuse Byte: --"
cat high.txt
echo
echo "-- Low Fuse Byte: --"
cat low.txt
echo

# 
# Example #1: (16MHz)
# -- High Fuse Byte: --
# S1040000DF1C
# S9030000FC
# 
# -- High Fuse Byte: --
# S1040000E11A
# S9030000FC
# 
#
# Example #2: (8MHz)
# -- High Fuse Byte: --
# S1040000DF1C
# S9030000FC
# 
# -- Low Fuse Byte: --
# S10400006299
# S9030000FC
# 

# 16MHz   E1  (+ set CLOCK at beginning)
#  8MHz   E1  (disable CKDIV8)
#  1MHz   62

if test $PROGRAM_FUSES -eq 1
then
  if avrdude -c $PGM_PROTO -P $PORT -p $PGM_DEVICE -U lfuse:w:0xE1:m
  then
    echo " ***  FUSES SUCCESSFULLY PROGRAMMED ***"
    echo " ***  FUSES SUCCESSFULLY PROGRAMMED ***"
    echo " ***  FUSES SUCCESSFULLY PROGRAMMED ***"
  else
    echo "programming fuses failed!"
    echo "programming fuses failed!"
    echo "programming fuses failed!"
    exit 1
  fi
fi



#
#   UPLOAD PROGRAM TO MCU
#

if avrdude -c $PGM_PROTO -P $PORT -p $PGM_DEVICE -U flash:w:$PROJECT.hex 
then
  echo " ***  READY ***"
else
  echo "failed!"
  exit 1
fi
